/**
 * Copyright 2010 Nicholas Alexander Cross
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dataporter.processing;

import org.dataporter.data.DataObject;
import org.dataporter.data.DataUpdate;
import org.dataporter.data.DataUpdateType;

import java.util.*;

public class FieldExposer implements DataProcessor {

    private final Map<String, List<String>> fieldNames;

    public FieldExposer( Map<String, List<String>> fieldNames ) {
        this.fieldNames = fieldNames;
    }

    public List<DataUpdate> process( DataObject object ) throws DataProcessingException {
        ArrayList<DataUpdate> list = new ArrayList<DataUpdate>();

        Set<String> entityNames = fieldNames.keySet();

        for ( String entityName : entityNames )
        {
            List<String> fieldNamesForEntity = fieldNames.get( entityName );

            HashMap<String, Object> changes = new HashMap<String, Object>();
            
            for ( String fieldName : fieldNamesForEntity )
            {
                changes.put( fieldName, object.get( fieldName ) );
            }

            DataUpdate update = null;
            List<String> primaryKeyNames = object.getPrimaryKeyNames();

            if ( primaryKeyNames == null )
            {
                update = new DataUpdate( entityName, DataUpdateType.Append, null, changes );
            }
            else
            {
                if ( object.isNew() )
                {
                    update = new DataUpdate( entityName, DataUpdateType.Insert, primaryKeyNames, changes );
                }
                else
                {
                    update = new DataUpdate( entityName, DataUpdateType.Update, primaryKeyNames, changes );
                }

            }

            list.add( update );
        }


        return list;
    }

}
